
import sys
sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests
from common.helper import Helper
from urllib.parse import urlencode


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "e康安泰重大疾病保险"
    #生成产品数据
    def genProductInfo(self):
        plan = {
            "planA":{
                # 年龄段
                "year":[str(i) for i in range(0,56)],
                #性别
                "gender":["M","F"],
                #保障期限
                "expire":["1年"],
                #交费类型
                "payType":["年交"],
                #保障金额
                "money":["50000"]
            },
            "planB":{
                # 年龄段
                "year": [str(i) for i in range(0, 56)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 保障金额
                "money": ["100000"]

            },
            "planC": {
                # 年龄段
                "year": [str(i) for i in range(0, 56)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 保障金额
                "money": ["200000"]

            },
            "planD": {
                # 年龄段
                "year": [str(i) for i in range(0, 56)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 保障金额
                "money": ["300000"]

            }
        }
        for k in plan:
            for v in product(plan[k]["year"],plan[k]["gender"],plan[k]["expire"],plan[k]["payType"],plan[k]["money"]):
                data = Helper.formatProductInfo( plan[k], v )
                self.mysql.cursor.execute( domain[self.name]["insert_sql"].format( **data ))
                self.mysql._conn.commit()
                print( domain[self.name]["insert_sql"].format( **data ) )

    #执行爬虫
    def requestJson(self,dt=None):

        if dt["money"] == "50000":
            categoryCode = "100009"
        elif dt["money"] == "100000":
            categoryCode = "100007"
        elif dt["money"] == "200000":
            categoryCode = "100010"
        else:
            categoryCode = "100008"

        data = {
            "rqstType":"AJAX",
            "chnlId":"23",
            "packageCode":"100004",
            "socialFlag":"2",
            "benefit":"1",
            "unit":"y",
            "birthday":"{0}-01-01".format( str(int(2020-int(dt["year"])))),
            "sex":"0" if dt["gender"] == "M" else "1",
            "categoryCode":categoryCode
        }
        payload = urlencode(data).replace("+","")
        r= requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload,verify=False)
        if r.status_code == 200 and "成功" in r.text :
            price = r.json()["defmap"]["price"]
            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            print( data )
            self.mysql.updatePrice( data )
        else:
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            self.mysql.updateTask( data )
            print("\n/*产品价格更新失败:%d*/"%dt["id"])
    def main(self):
        while True:
            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)
            if not dt:
                print("产品价格抓取完成~~~")
                return
                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)
            self.requestJson(dt)
